package message.types.data;

import java.io.IOException;

import message.Message;
import message.visitor.MessageVisitor;
import network.e2e.FrameReader;
import network.e2e.FrameWriter;
import stalker.Stalker;
import data.Data;
import data.DataParser;

public class GetLastDataAnswer extends Message {
  
  private final Data data_;
  
  /**
   * Constructs an answer for GetLastDataRequest
   * @requires parameters not null
   * @param client      The answerer
   * @param destination The recipient
   * @param data        The answer
   */
  
  public GetLastDataAnswer(Stalker client, Stalker destination, Data data) {
    super(client, destination);
    assert data != null;
    data_ = data;
  }
  
  /**
   * Retrieve data from the net
   * @requires parameters not null
   * @param client      The answerer
   * @param destination The recipient
   * @param reader      The net
   * @throws IOException 
   */
  
  public GetLastDataAnswer(Stalker client, Stalker destination, FrameReader reader) throws IOException {
    super(client, destination);
    assert reader != null;
    data_ = DataParser.retrieve(reader);
  }
  
  /**
   * Retrieves the answer
   * @return the answer
   */
  public Data getAnswer() {
    return data_;
  }
  
  @Override
  public String toString() {
    return "GetLastDataAnswer. From: " + this.getClient() + " To: " + this.getDestination() + " Is: " + this.getAnswer();
  }

  @Override
  public <T> T accept(MessageVisitor<T> visitor) {
    return visitor.visit(this);
  }

  @Override
  public void send(FrameWriter writer) throws IOException {
    DataParser.send(data_, writer);
  }

  @Override
  public boolean equals(Object obj) {
    if (!(obj instanceof GetLastDataAnswer)) {
      return false;
    }
    GetLastDataAnswer that = (GetLastDataAnswer) obj;
    return this.getClient().equals(that.getClient()) &&
           this.getDestination().equals(that.getDestination()) &&
           this.getAnswer().equals(that.getAnswer());
  }

}
